//
//  NSDate+Extension.swift
//  WangFangWeiBo
//
//  Created by 王方 on 16/7/16.
//  Copyright © 2016年 wf. All rights reserved.
//

import UIKit

extension NSDate {
    //根据时间字符串创建时间对象
    class func sinaDate(createAtStr:String)->NSDate {
        let dt = NSDateFormatter()
        dt.dateFormat = "EEE MMM dd HH:mm:ss z yyyy"
        dt.locale = NSLocale(localeIdentifier: "en_US")
        let createAtDate = dt.dateFromString(createAtStr)
        return createAtDate!
    }
    
    //判断是否是今年
    private func isThisYear(createAtDate:NSDate)->Bool{
         let dt = NSDateFormatter()
         dt.dateFormat = "yyyy"
         dt.locale = NSLocale(localeIdentifier: "en_US")
         let createDateYear = dt.stringFromDate(createAtDate)
         let currentDateYear = dt.stringFromDate(NSDate())
        return createDateYear == currentDateYear
        
    }
    
    //根据时间对象转换成字符串
    var sinaDateString:String {
        
          let dt = NSDateFormatter()
         dt.locale = NSLocale(localeIdentifier: "en_US")
        if isThisYear(self) {
            //如果是今年
            //判断是不是今天
            let calender = NSCalendar.currentCalendar()
            
            if calender.isDateInToday(self){
                //如果是今天
            let time = abs(self.timeIntervalSinceNow)
                if time < 60 {
                    return "刚刚"
                }else if time < 60 * 60 {
                    let result = time / 60
                    
                    return "\(Int(result))分钟前"
                }else {
                    // 秒转换成小时
                    let result = time / 3600
                    return "\(Int(result))小时前"
                }
                
            }else if calender.isDateInYesterday(self){
                //如果是昨天
                dt.dateFormat = "昨天 HH:mm"
            }else{
                //其他
                dt.dateFormat = "MM-dd HH:mm"
            }
            
            
        }else{
            //如果不是今年
            dt.dateFormat =  "yyyy-MM-dd HH:mm"
        }
        return dt.stringFromDate(self)
    }
    
    
}
